/*
 * @lc app=leetcode.cn id=513 lang=cpp
 *
 * [513] 找树左下角的值
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    int findBottomLeftValue(TreeNode *root) {
        int ans = 0;
        queue<TreeNode *> tree;
        tree.push(root);

        // BFS
        while (!tree.empty()) {
            // 记录该层的最左边的节点的值
            ans = (tree.front())->val;

            // 取出该层的所有节点，并将其子节点加入队列
            int length = tree.size();
            for (int i = 0; i < length; i++) {
                TreeNode *node = tree.front();
                tree.pop();
                if (node->left != nullptr) tree.push(node->left);
                if (node->right != nullptr) tree.push(node->right);
            }
        }

        return ans;
    }
};
// @lc code=end
